import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken, getRefreshToken, setToken, clearUserData } from '@/utils/auth'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || 'http://localhost:8000',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 刷新token的函数
let isRefreshing = false
let failedQueue = []

const processQueue = (error, token = null) => {
  failedQueue.forEach(prom => {
    if (error) {
      prom.reject(error)
    } else {
      prom.resolve(token)
    }
  })

  failedQueue = []
}

const refreshToken = async () => {
  const refreshTokenValue = getRefreshToken()
  if (!refreshTokenValue) {
    throw new Error('No refresh token available')
  }

  try {
    const response = await axios.post(`${process.env.VUE_APP_BASE_API || 'http://localhost:8000'}/api/auth/token/refresh/`, {
      refresh: refreshTokenValue
    })

    if (response.data && response.data.access) {
      setToken(response.data.access)
      return response.data.access
    } else {
      throw new Error('Invalid refresh response')
    }
  } catch (error) {
    console.error('Token refresh failed:', error)
    throw error
  }
}

// 请求拦截器
service.interceptors.request.use(
  config => {
    console.log('发送请求:', config.url, config)
    
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log('收到响应:', response.config.url, response.data)
    
    const res = response.data
    
    // 如果响应格式不是标准格式，直接返回
    if (typeof res !== 'object' || res === null) {
      return response
    }
    
    // 检查是否有success字段
    if (res && typeof res === 'object' && 'success' in res) {
      return res
    }
    
    // 兼容其他格式
    return res
  },
  async error => {
    console.error('响应错误:', error)

    const originalRequest = error.config

    if (error.response) {
      const { status, data } = error.response

      if ((status === 401 || status === 403) && !originalRequest._retry) {
        if (isRefreshing) {
          // 如果正在刷新token，将请求加入队列
          return new Promise((resolve, reject) => {
            failedQueue.push({ resolve, reject })
          }).then(token => {
            originalRequest.headers['Authorization'] = `Bearer ${token}`
            return service(originalRequest)
          }).catch(err => {
            return Promise.reject(err)
          })
        }

        originalRequest._retry = true
        isRefreshing = true

        try {
          const newToken = await refreshToken()
          processQueue(null, newToken)
          originalRequest.headers['Authorization'] = `Bearer ${newToken}`
          return service(originalRequest)
        } catch (refreshError) {
          processQueue(refreshError, null)
          ElMessage.error('登录已过期，请重新登录')
          clearUserData()
          router.push('/login')
          return Promise.reject(refreshError)
        } finally {
          isRefreshing = false
        }
      } else if (status === 403 && originalRequest._retry) {
        // 如果已经尝试过刷新token但仍然403，说明是权限问题
        ElMessage.error('没有权限访问')
      } else if (status >= 500) {
        ElMessage.error('服务器错误')
      } else {
        ElMessage.error(data?.message || '请求失败')
      }
    } else {
      ElMessage.error('网络错误')
    }

    return Promise.reject(error)
  }
)

export default service 


